package cn.dakaqi.pingan.util;

import cn.dakaqi.entities.PinganActivate;
import cn.dakaqi.entities.PinganOpen;
import cn.dakaqi.entities.PinganVoucherCenter;
import cn.dakaqi.entities.VolunteerInsurance;
import cn.dakaqi.pingan.entities.ActivateResult;
import cn.dakaqi.pingan.services.PinganActivateService;
import cn.dakaqi.pingan.services.PinganNumberService;
import cn.dakaqi.pingan.services.PinganOpenService;
import cn.dakaqi.pingan.services.PinganVoucherCenterService;
import cn.dakaqi.utils.Clock;
import cn.dakaqi.utils.DateUtil;
import cn.dakaqi.utils.http.HttpInvoker;
import cn.dakaqi.volunteer.insurance.services.VolunteerInsuranceService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author chunyang on 2016/2/17.
 */
@Component(value = "activateCard")
@Transactional
public class ActivateCard {
    private static Logger logger = LoggerFactory.getLogger(ActivateCard.class);
    @Autowired
    PinganNumberService pinganNumberService;
    @Autowired
    PinganActivateService pinganActivateService;
    @Autowired
    PinganOpenService pinganOpenService;
    @Autowired
    PinganVoucherCenterService pinganVoucherCenterService;
    @Autowired
    VolunteerInsuranceService volunteerInsuranceService;

    /**
     * 3.2 激活电子卡
     *
     * @param type    类型
     * @param cardNum 卡号
     * @throws Exception
     */
    public ActivateResult activate(String type, String volunteerCode, String cardNum) throws Exception {
        //检查当前电子卡是否已激活

        ActivateResult result;
        String callBackUrl = "<![CDATA[" + PingAnUtil.callBackUrl + volunteerCode + ";" + cardNum + "]]>";
        //激活时的XML
        //String activateXML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><ROOT><cardNo>"+cardNum+"</cardNo><callBackUrl>"+PingAnUtil.callBackUrl+volunteerCode+";cardNum="+cardNum+"</callBackUrl></ROOT>";
        String activateXML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><ROOT><cardNo>" + cardNum + "</cardNo><callBackUrl>" + callBackUrl + "</callBackUrl></ROOT>";
        System.out.println("---------------------平安激活操作开始------------" + DateUtil.getToday());
        //查询当前类型，当天目前最大编号+1 的流水号
        String sn = pinganNumberService.createNO(type);
        //A001字符开头，即如下定义的222报文头。
        String head = MessageHead.A001(activateXML, sn, PingAnUtil.tradeNO000002, PingAnUtil.shopNO);
        System.out.println("激活银行卡时,报文头长度为" + head.length() + "报文内容:" + head);
        //提交至平安银行
        String content = head + activateXML;
        System.out.println("激活银行卡时,提交的数据为:" + content);
        String retValue = HttpInvoker.httpPostXML(PingAnUtil.B2BiUrl, content);
        System.out.println("激活银行卡时,返回信息:" + retValue);
        //截取银行返回的XML结果
        String xmlStr = retValue.substring(222, retValue.length());
        System.out.println("激活银行卡时,去除报文头后的信息:" + xmlStr);
        //将银行返回的XML组装银行开户数据对象
        result = ParseXML.activateResult(xmlStr);
        System.out.println(result.toString());
        if (null != result)
        {
            PinganActivate pinganActivate = pinganActivateService.findByCardNum(cardNum);
            if (null == pinganActivate)
            {
                //保存激活记录
                pinganActivate = new PinganActivate();
                pinganActivate.setCreateTime(Clock.DEFAULT.getCurrentDate());
                pinganActivate.setCardNum(cardNum);
                pinganActivate.setSn(sn);
                pinganActivate.setStatus(result.getState());
                this.pinganActivateService.save(pinganActivate);
            }
        }
        System.out.println("---------------------平安激活操作结束------------" + DateUtil.getToday());
        return result;
    }

    /**
     * 修改指定流水号的激活状态
     *
     * @param volunteerCode 用户编码
     * @param cardNum 卡号
     * @throws Exception
     */
    public void updateActivateRecord(String volunteerCode, String cardNum) throws Exception {
        //修改指定账户开户成功状态
        PinganOpen pinganOpen = pinganOpenService.findByCardNumAndStatus(cardNum, PinganOpen.STATUS_NO);
        pinganOpen.setStatus(PinganOpen.STATUS_YES);
        pinganOpenService.save(pinganOpen);

        //保存平安银行充值中心待充值
        PinganVoucherCenter pinganVoucherCenter = new PinganVoucherCenter();
        pinganVoucherCenter.setStatus(0);
        pinganVoucherCenter.setCardNum(cardNum);
        pinganVoucherCenter.setCreateTime(Clock.DEFAULT.getCurrentDate());
        pinganVoucherCenter.setMoney(0f);
        pinganVoucherCenter.setMoneyTime(null);
        this.pinganVoucherCenterService.save(pinganVoucherCenter);

        //检查当前用户是否已购买过保险
        VolunteerInsurance insurance = volunteerInsuranceService.findByVolunteerCodeAndStatus(volunteerCode, VolunteerInsurance.STATUS_ACTIVATION);
        if (null == insurance) {
            //购买保险操作
            {
                //执行购买保险操作后，返回我的保单界面
                if (StringUtils.isBlank(pinganOpen.getGuardianName()))
                    volunteerInsuranceService.applyInsurance(volunteerCode, pinganOpen.getName(), pinganOpen.getIdCard(), pinganOpen.getMobile());
                else
                    volunteerInsuranceService.applyInsurance(volunteerCode, pinganOpen.getGuardianName(), pinganOpen.getGuardianIDCard(), pinganOpen.getGuardianMobile());
            }
        }
    }
}
